package com.example.controller;

import com.example.dto.QuestionRequest;
import com.example.model.Question;
import com.example.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/questions")
@CrossOrigin
public class QuestionController {
    
    @Autowired
    private QuestionService questionService;
    
    @PostMapping
    public Question addQuestion(@RequestBody QuestionRequest request) {
        return questionService.createQuestion(request.getQuestion(), request.getAnswer());
    }
    
    @PostMapping("/{id}/collect")
    public Question toggleCollect(@PathVariable Long id, @RequestBody Map<String, Boolean> request) {
        boolean isCollected = request.get("isCollected");
        return questionService.updateCollectStatus(id, isCollected);
    }
    
    @PostMapping("/{id}/regenerate")
    public Question regenerateAnswer(@PathVariable Long id) {
        return questionService.regenerateAnswer(id);
    }
    
    @PostMapping("/{id}/learned")
    public Question toggleLearned(@PathVariable Long id) {
        questionService.toggleLearned(id);
        return questionService.findById(id);
    }
    
    @GetMapping("/learning-list")
    public List<Question> getLearningList(@RequestParam String topic) {
        return questionService.generateLearningList(topic);
    }

    @GetMapping
    public List<Question> getAllQuestions() {
        return questionService.getAllQuestions();
    }

    @GetMapping("/search")
    public List<Question> searchQuestions(@RequestParam String keyword) {
        return questionService.searchQuestions(keyword);
    }

    @GetMapping("/statistics")
    public Map<String, Object> getStatistics() {
        return questionService.getStatistics();
    }
    
    @PostMapping("/{id}/difficulty")
    public void updateDifficulty(@PathVariable Long id, @RequestParam int difficulty) {
        questionService.updateDifficulty(id, difficulty);
    }
    
    @GetMapping("/topics")
    public List<String> getAllTopics() {
        return questionService.getAllTopics();
    }

    @GetMapping("/learned")
    public List<Question> getLearnedQuestions() {
        return questionService.getLearnedQuestions();
    }

    @GetMapping("/stream/{id}")
    public SseEmitter streamAnswer(@PathVariable Long id) {
        return questionService.streamAnswer(id);
    }
    
    @GetMapping("/stream")
    public SseEmitter streamNewAnswer(@RequestParam String question) {
        return questionService.streamNewAnswer(question);
    }

    @DeleteMapping("/{id}")
    public void deleteQuestion(@PathVariable Long id) {
        questionService.deleteQuestion(id);
    }
} 